package monster.com.cvh.fragment;

import android.app.Activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import monster.com.cvh.R;
import monster.com.cvh.adapter.EducationAdapter;
import monster.com.cvh.bean.EducationBean;
import monster.com.cvh.bean.ResultBean;
import monster.com.cvh.event.RefreshCompletedEvent;
import monster.com.cvh.fragment.base.ResumeInfoBaseFragment;
import monster.com.cvh.listener.OnHideKeyBoardListener;
import monster.com.cvh.util.CheckNetUtils;
import monster.com.cvh.util.KeyboardUtils;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: 13580
 * @data: 2018/3/19
 * @function:教育经历fragment
 */

public class EducationFragment extends ResumeInfoBaseFragment {
    private static final String TAG = "EducationFragment";
    @BindView(R.id.tv_include_top_bar_title)
    TextView mTVTitle;
    @BindView(R.id.rv_activity_education)
    RecyclerView mRecyclerView;
    private EducationAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private List<EducationBean.DataBean> mBean;
    private List<EducationBean.DataBean> mCloneBean = new ArrayList<>();

    public static EducationFragment newInstance() {
        EducationFragment fragment = new EducationFragment();
        return fragment;
    }

    @Override
    protected void initEvent() {
        mTVTitle.setText(getResources().getString(R.string.fragment_education_title));
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_user_msg_common;
    }


    @Override
    protected void initData() {
        mDialog.show();
        OkGo.<String>get(MyConstant.GET_RESUME_EDUCATION_EXP).tag(this)
                .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e(TAG, "获取教育经历: " + s);
                        try {
                            EducationBean bean = new Gson().fromJson(s, EducationBean.class);
                            if (bean != null && bean.getCode() == 1) {
                                mBean = (ArrayList<EducationBean.DataBean>) bean.getData();
                                if (mBean.size()==0){
                                    mBean.add(new EducationBean.DataBean(0));
                                }
                                mCloneBean = deepCopyList(mBean);
                                initViewData();
                            } else {
                                showToastShort(R.string.net_load_failed);
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                            showToastShort(R.string.net_load_failed);
                        } finally {
                            mDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mDialog.dismiss();
                        showToastShort(R.string.net_load_failed);
                    }
                });
    }

    private void initViewData() {
        mAdapter = new EducationAdapter(mBean, (OnHideKeyBoardListener) this);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        //添加尾部
        View footer = LayoutInflater.from(getActivity()).inflate(R.layout.item_user_msg_common_footer, null, true);
        footer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.addData(new EducationBean.DataBean(mAdapter.getData().size()));
                mAdapter.notifyDataSetChanged();
            }
        });
        mAdapter.addFooterView(footer);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    @OnClick({R.id.iv_include_top_bar_back, R.id.tv_include_top_bar_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_include_top_bar_back:
                isSaveOnExit();
                break;
            case R.id.tv_include_top_bar_save:
                saveInfoData();
                break;
        }
    }

    private void isSaveOnExit() {
        if (!isDataChanged()) {
            mAlertDialog.show();
        } else {
            KeyboardUtils.hideSoftInput((Activity) mContext);
            ((Activity)mContext).finish();
        }
    }

    @Override
    protected void saveInfoData() {
        if (!CheckNetUtils.checkState_21()){
            InfoUnCompeledDialogFragment.getInstance(getString(R.string.net_offline)).show(getFragmentManager(),"net_offline");
            return;
        }
        if (mAdapter != null) {
            if (mAdapter.getData().size()==0){
                KeyboardUtils.hideSoftInput((Activity) mContext);
                ((Activity)mContext).finish();
                return;
            }
            String infoCompleted = mAdapter.checkInfoCompleted();
            if (infoCompleted != null) {
                InfoUnCompeledDialogFragment.getInstance(infoCompleted).show(getFragmentManager(), "dialog_info_tips");
            } else {
                mDialog.show();
                ArrayList<EducationBean.DataBean> dataBeans = new ArrayList<>(mAdapter.getData());
                for (int i = 0; i < dataBeans.size(); i++) {
                    EducationBean.DataBean bean = dataBeans.get(i);
                    bean.setId(i);
                    String enrollTime = bean.getEnroll_time();
                    String graduateTime = bean.getGraduate_time();
                    if (enrollTime.length()>0&&!enrollTime.contains("年")) {
                        bean.setEnroll_time(enrollTime.substring(0, 4) + "年" + enrollTime.substring(5, 7) + "月");
                    }
                    if (graduateTime.length()>0&&!graduateTime.contains("年")) {
                        bean.setGraduate_time(graduateTime.substring(0, 4) + "年" + graduateTime.substring(5, 7) + "月");
                    }
                    Log.e("qqq", "Adapter的数据: "+new Gson().toJson(dataBeans));
                }
                String json = new Gson().toJson(dataBeans);
//                Log.e(TAG, "保存的数据: " + json);
                OkGo.<String>put(MyConstant.MODIFY_RESUME_EDUCATION_EXP).tag(this)
                        .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                        .params(MyConstant.ITEMS, json)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Log.e(TAG, "保存的数据成功: " + s);
                                try {
                                    ResultBean resultBean = new Gson().fromJson(s, ResultBean.class);
                                    if (resultBean.getCode() == 1) {
                                        showToastShort(R.string.net_save_success);
                                        //通知刷新完成度
                                        RefreshCompletedEvent.getInstance().onRefreshCompleted();
                                        getActivity().finish();
                                    } else {
                                        showToastShort(R.string.net_load_failed);
                                    }
                                } catch (JsonSyntaxException e) {
                                    e.printStackTrace();
                                    showToastShort(R.string.net_load_failed);
                                } finally {
                                    mDialog.dismiss();
                                    KeyboardUtils.hideSoftInput((Activity) mContext);
                                }
                            }

                            @Override
                            public void onError(Call call, Response response, Exception e) {
                                super.onError(call, response, e);
                                showToastShort(R.string.net_load_failed);
                                mDialog.dismiss();
                            }
                        });
            }
        }
    }

    @Override
    public boolean isDataChanged() {
        if (mCloneBean==null||mBean==null){
            return true;
        }
        if (mCloneBean.size() != mBean.size()) {
            return false;
        }
        for (int i = 0; i < mCloneBean.size(); i++) {
            EducationBean.DataBean clone = mCloneBean.get(i);
            EducationBean.DataBean bean = mBean.get(i);
            if (!clone.equals(bean)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onExit() {
        isSaveOnExit();
    }
}
